package com.sky.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.admin.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Autowired private JwtProperties jwtProperties;
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public Map<String, Object> findAllPage(String name, Integer page, Integer pageSize) {
        Page<Employee> employeePage = new Page<>(page, pageSize);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            employeeQueryWrapper.eq("name", name);
        }
        IPage<Employee> result = employeeMapper.selectPage(employeePage, employeeQueryWrapper);
        List<Employee> records = result.getRecords();
        long total = result.getTotal();
        stringObjectHashMap.put("total", total);
        stringObjectHashMap.put("records", records);

        return stringObjectHashMap;
    }

    @Override
    public void editPassword(@RequestBody PasswordEditDTO passwordEditDTO) {
        Result<Object> objectResult = new Result<>();
        if (passwordEditDTO == null){
            throw new RuntimeException("参数为null");
        }
        //请求头中获取token反获取id，因为lj前端不给我直接传id
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String cookie = request.getHeader("cookie");
        String[] split = cookie.split(";");
        String token = split[2].substring(7);
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Integer empId = Integer.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
        passwordEditDTO.setEmpId(empId);
        Employee employee = employeeMapper.selectById(passwordEditDTO.getEmpId());

        log.info("employee:"+employee);
        if (!passwordEditDTO.getOldPassword().equals(employee.getPassword())){
            log.info("旧密码错误"+passwordEditDTO.getOldPassword());
            objectResult.setMsg("旧密码错误");
        }
        employee.setPassword(passwordEditDTO.getNewPassword());
        employeeMapper.updateById(employee);
    }


}
